package com.gxcc3.ygps.system.service.impl;

import com.gxcc3.ygps.common.core.domain.ExcelColumn;
import com.gxcc3.ygps.common.core.domain.ExcelColumnSelect;
import com.gxcc3.ygps.common.core.domain.ImportData;
import com.gxcc3.ygps.common.core.domain.TreeSelect;
import com.gxcc3.ygps.common.core.domain.entity.SysCheckDetection;
import com.gxcc3.ygps.common.core.domain.entity.SysCheckDetectionItem;
import com.gxcc3.ygps.common.core.domain.entity.SysCheckItem;
import com.gxcc3.ygps.common.core.domain.entity.SysIotStorage;
import com.gxcc3.ygps.common.exception.ServiceException;
import com.gxcc3.ygps.common.exception.UtilException;
import com.gxcc3.ygps.common.utils.MessageUtils;
import com.gxcc3.ygps.common.utils.StringUtils;
import com.gxcc3.ygps.common.utils.poi.ExcelUtil;
import com.gxcc3.ygps.common.utils.uuid.IdUtils;
import com.gxcc3.ygps.system.mapper.SysCheckDetectionItemMapper;
import com.gxcc3.ygps.system.mapper.SysCheckDetectionMapper;
import com.gxcc3.ygps.system.mapper.SysCheckItemMapper;
import com.gxcc3.ygps.system.service.ISysCheckDetectionService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.hibernate.validator.internal.util.StringHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysCheckDetectionServiceImpl implements ISysCheckDetectionService {

    @Resource
    SysCheckDetectionMapper detectionMapper;

    @Resource
    SysCheckDetectionItemMapper detectionItemMapper;

    @Resource
    SysCheckItemMapper itemMapper;

    /**
     * 工作薄对象
     */
    private Workbook wb;



    /**
     * 查询检测列表
     * @param detection 查询参数
     * @return 返回结果
     */
    @Override
    public List<SysCheckDetection> selectDetectionList(SysCheckDetection detection) {
        return detectionMapper.selectDetectionList(detection);
    }


    /**
     * 录入检测
     * @param detection 参数
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDetection(SysCheckDetection detection) {
        List<SysCheckDetectionItem> itemList = detection.getItemList();
        String detectionId = IdUtils.simpleUUID();
        detection.setDetectionId(detectionId);
        if (StringUtils.isEmpty(itemList)){
            throw new ServiceException("操作失败");
        }
        for (SysCheckDetectionItem map : itemList) {
            map.setDetectionId(detectionId);
        }
        int row = detectionMapper.insertDetection(detection);
        detectionItemMapper.insertDetectionItem(itemList);
        return row;
    }


    /**
     * 删除检测
     * @param ids 参数
     * @return 结果
     */
    @Override
    public int delDetection(Long[] ids) {
        return detectionMapper.delDetection(ids);
    }


    /**
     * 获取检测详情
     * @param id 参数
     * @return 结果
     */
    @Override
    public SysCheckDetection selectDetectionById(Long id) {
        SysCheckDetection detection = detectionMapper.selectDetectionById(id);
        String detectionId = detection.getDetectionId();
        detection.setItemList(detectionItemMapper.selectDetectionItemList(detectionId));
        return detection;
    }


    /**
     * 获取导出模板
     * @return 结果
     */
    @Override
    public List<ExcelColumn> importTemplate() {
        return buildImportTemplate();
    }

    /**
     * 构建导出的excel模板
     * @return 结果
     */
    private List<ExcelColumn> buildImportTemplate() {
        List<ExcelColumn> list = new ArrayList<>();
        list.add(new ExcelColumn("商品名称(必填)","goodsName", ExcelColumn.ColumnType.STRING,true));
        List<SysCheckItem> itemList = itemMapper.selectItemListAll();
        List<ExcelColumnSelect> itemSelect = itemList.stream().map(ExcelColumnSelect::new).collect(Collectors.toList());
        list.add(new ExcelColumn("检测项目(必填)","itemName", ExcelColumn.ColumnType.SELECT,true,itemSelect));
        List<ExcelColumnSelect> resultSelect = new ArrayList<>();
        resultSelect.add(new ExcelColumnSelect("合格","1"));
        resultSelect.add(new ExcelColumnSelect("不合格","2"));
        list.add(new ExcelColumn("检测结果(必填)","result", ExcelColumn.ColumnType.SELECT,true,resultSelect));
        list.add(new ExcelColumn("检测时间(必填)(yyyy-MM-dd HH:mm:ss)","checkTime", ExcelColumn.ColumnType.DATE,true));
        list.add(new ExcelColumn("检测值","checkTime", ExcelColumn.ColumnType.STRING,false));
        return list;
    }

    /**
     * 解析检测导入数据
     * @param is 文件输入流
     * @return 结果
     */
    @Override
    public ImportData importExcel(InputStream is) throws Exception{
        this.wb = WorkbookFactory.create(is);
        //定义初始值
        String uploadId = IdUtils.simpleUUID();
        long uploadTotal,successTotal,errorTotal = 0L;
        List<SysCheckDetection> successData = new ArrayList<>();
        List<SysCheckDetection> errorData = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //定义表头
        String[] title = {"检测商品","检测项目","检测结果","检测值","检测时间","备注","检测项目对应结果"};

        Sheet sheet = wb.getSheetAt(0);
        // 获取最后一个非空行的行下标，比如总行数为n，则返回的为n-1

        int rows = sheet.getLastRowNum();
        int startRow = 2;
        for (int i = 1; i <= rows; i++) {
            // 从第2行开始取数据,默认第一行是表头.
            Row row = sheet.getRow(i);
            // 判断当前行是否是空行
            if (ExcelUtil.isRowEmpty(row))
            {
                continue;
            }
            StringJoiner rowMessage = new StringJoiner(",");
            SysCheckDetection entity = new SysCheckDetection();

            String goodsName = ExcelUtil.getCellValue(row, 0).toString();
            String itemName = ExcelUtil.getCellValue(row,1).toString();
            String result = ExcelUtil.getCellValue(row,2).toString();
            String checkValue = ExcelUtil.getCellValue(row,3).toString();
            String checkTime = ExcelUtil.getCellValue(row,4).toString();
            String remark = ExcelUtil.getCellValue(row,5).toString();
            String itemResult = ExcelUtil.getCellValue(row,6).toString();
            if (StringUtils.isEmpty(goodsName)){
                rowMessage.add("商品名称为空");
            }
            entity.setGoodsName(goodsName);
            if (StringUtils.isEmpty(itemName)){
                rowMessage.add("检测项目为空");
            }
            entity.setItemName(itemName);
            if (StringUtils.isEmpty(result)){
                rowMessage.add("检测结果为空");
            }
            entity.setResult("合格".equals(result) ? "1" : "2");
            if (StringUtils.isEmpty(checkTime)){
                rowMessage.add("检测时间为空");
            }else {
                try {
                    LocalDateTime parseTime = LocalDateTime.parse(checkTime, df);
//                    entity.setCheckTime(Date.from(parseTime.atZone(ZoneId.systemDefault()).toInstant()));
                }catch (Exception e){
                    rowMessage.add("检测时间解析错误");
                }
            }
            entity.setCheckValue(checkValue);
            entity.setRemark(remark);
            //校验多项目对应结果
            List<String> itemNameList = Arrays.asList(itemName.split(","));
            List<String> itemResultList = Arrays.asList(itemResult.split(","));
            if (itemNameList.size() > 1 && StringUtils.isEmpty(itemResultList)){
                rowMessage.add("检测项目对应结果为空");
            }


        }

        return null;
    }
}
